package name.wilbur.course.db.bigone.ui.custom;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.Viewer;

public class ListContentProvider<T> implements IStructuredContentProvider,
		PropertyChangeListener {
	private ListViewer viewer;
	private ListModel<T> model;

	public ListContentProvider(ListViewer viewer) {
		this.model = new ListModel<T>();
		this.viewer = viewer;
	}
	
	@Override
	public Object[] getElements(Object inputElement) {
		return model.elements();
	}

	@Override
	public void dispose() {
	}

	@SuppressWarnings("unchecked")
	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		this.viewer = (ListViewer) viewer;
		if (oldInput instanceof ListModel)
			((ListModel<T>) oldInput).removePropertyChangeListener(this);
		if (newInput instanceof ListModel) {
			this.model = (ListModel<T>) newInput;
			((ListModel<T>) newInput).addPropertyChangeListener(this);
		}
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (ListModel.ADD_ELEMENT.equals(evt.getPropertyName()))
			viewer.add(evt.getNewValue());
		if (ListModel.REMOVE_ELEMENT.equals(evt.getPropertyName()))
			viewer.remove(evt.getNewValue());
	}
}
